package com.base.service.Impl;

import com.base.config.BaseException;
import com.base.config.BaseExceptionEnums;
import com.base.http.ErrType;
import com.base.http.ResultMap;
import com.base.service.FileUploadService;
import com.base.util.FileUploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private static final String basePath = "/Assets";
    private static final String separator = "/";

    @Value("${server.domainName}")
    private String domainName;

    @Override
    public ResultMap singleUpload(MultipartFile file, String path) {
        if (file.isEmpty()) {
            BaseException.throwSystemException(BaseExceptionEnums.FILE_EMPTY);

        }

        String url = StringUtils.EMPTY;
        try {
            url = FileUploadUtil.writeFile(file.getBytes(), String.format("%s/%s/", basePath, path),
                    file.getOriginalFilename());

        } catch (IOException e) {
            BaseException.throwSystemException(BaseExceptionEnums.FILE_UPLOAD_FAIL);
        }

        return new ResultMap(ErrType.SUCCESS,getFullUrl(url));
    }

    @Override
    public String getFullUrl(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return "";
        }

        return domainName + filePath;
    }
}
